package top.xana.acg.anime.utils

import android.content.Context
import com.google.gson.reflect.TypeToken
import top.xana.acg.anime.App

object XmlCache {

    private const val DEFAULT_CACHE_FILENAME = "default_cache_filename"

    @JvmStatic
    fun <T> write(
        key: String,
        value: T,
        filename: String = DEFAULT_CACHE_FILENAME,
        ctx: Context = App.app,
        async: Boolean = true
    ): Boolean? {
        val sp = ctx.getSharedPreferences(filename, Context.MODE_PRIVATE)
        val editor = sp.edit()
        when (value) {
            is String -> editor.putString(key, value)
            is Collection<*> -> editor.putStringSet(key, value.map { "$it" }.toSet())
            is Int -> editor.putInt(key, value)
            is Float -> editor.putFloat(key, value)
            is Long -> editor.putLong(key, value)
            else -> return null
        }
        return if (async) {
            editor.apply()
            null
        } else {
            editor.commit()
        }
    }

    @SuppressWarnings("all")
    @JvmStatic
    fun <T> read(
        key: String,
        filename: String = DEFAULT_CACHE_FILENAME,
        ctx: Context = App.app,
    ): T? {
        val sp = ctx.getSharedPreferences(filename, Context.MODE_PRIVATE)
        val tt = object : TypeToken<T>() {}
        return when (tt.type) {
            String::class.java -> sp.getString(key, null)
            Collection::class.java -> sp.getStringSet(key, null)
            Int::class.java -> sp.getInt(key, 0)
            Float::class.java -> sp.getFloat(key, 0f)
            Long::class.java -> sp.getLong(key, 0L)
            else -> null
        } as T
    }

    @JvmStatic
    fun clear(
        filename: String = DEFAULT_CACHE_FILENAME,
        ctx: Context = App.app
    ) {
        val sp = ctx.getSharedPreferences(filename, Context.MODE_PRIVATE)
        sp.edit().clear().apply()
    }

}